let sort_weight_url = "http://127.0.0.1:9666";

let weightUnit = 1;

let weightNum = 1;

const pattern = /^[A-Z]{2}[01]{1}[0-9]{9}$/;

//实时称重
//type:0:称重；1:报损
//flow:0:分拣；1:合箱
let sortSetInterval;

function sortWeightInfo(tableId, id, type, flow, obj, bigProduct) {
    //以obj判断，做最小改动，其他引用common.js页面只新增obj为null的参数，新增一个socketIo监听传obj非空即可
    //之后想用页面循坏读取，则取消oldWeight函数注解即可
    console.log("tableId:" + tableId + ";id:" + id + ";type:" + type + ";flow:" + flow + ";obj:" + JSON.stringify(obj));
    if (obj == null) {
        //旧方式，在页面上循环请求
        // oldWeight(tableId, id, type, flow,bigProduct);
    } else {
        //新方式，分拣电脑称重返回服务器，服务器socketIo返回页面
        newWeight(tableId, id, type, flow, obj, bigProduct);
    }
}

//实时称重
//type:0:称重；1:报损
//flow:0:分拣；1:合箱
//obj:服务器回传的称重数据对象
function newWeight(tableId, id, type, flow, obj, bigProduct) {
    const reValue = obj.weight;
    if (reValue != "-1") {
        $("#" + id).focus();
        if (flow == 0) {
            sortFrmLoseWeight(reValue, tableId, id, type, bigProduct);
        } else if (flow == 1) {
            mergeWeight(reValue, tableId, id, type, bigProduct)
        }
    }
}

function oldWeight(tableId, id, type, flow) {
    const wu = Cookies.get("wu");
    if (wu) {
        sort_weight_url = wu;
    }
    let comName = Cookies.get("comName");
    if (!comName) {
        comName = "COM3";
    }
    let delay = Cookies.get("delay");
    if (!delay) {
        delay = 300;
    }
    sortSetInterval = setInterval(function () {
        $.get(sort_weight_url + "/weight/read", {comName: comName}, function (reValue) {
            console.log("散装称重：" + reValue + "；id：" + id + "；type：" + type + "；flow" + flow + "；tableId：" + tableId);
            $("#" + id).focus();
            if (reValue != "-1") {
                $("#" + id).focus();
                if (flow == 0) {
                    sortFrmLoseWeight(reValue, tableId, id, type);
                } else if (flow == 1) {
                    mergeWeight(reValue, tableId, id, type)
                }
            }
        });
    }, delay);
}

Date.prototype.Format = function (fmt) {
    const o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (const k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//分拣/报损称重
//type:0:称重；1:报损
function sortFrmLoseWeight(reValue, tableId, id, type, bigProduct) {
    if (reValue != 0.000 && reValue > 0) {
        const str = reValue.replace(/\s*/g, "");
        // console.log(JSON.stringify(reValue.length));
        // console.log(JSON.stringify(str));
        // console.log(JSON.stringify(str.length));
        const rows = $('#' + tableId).bootstrapTable('getSelections');
        if (rows.length > 0) {
            const row = rows[0];
            if (row && row.spuId && row.weight) {
                const spuList = $('#box-list-table').bootstrapTable('filterBy', {spuId: [row.spuId]});
                if (spuList && spuList.length > 0) {
                    const bulk = spuList[0];
                    if (!bulk.inBulk && type == 0) {
                        //标品展示每份重量
                        // $('#sort-weight').attr("disabled", true);
                        $("#" + id).val((parseFloat(str) * weightNum * weightUnit).toFixed(2));
                    } else {
                        const weight = (parseFloat(str) * weightNum * weightUnit).toFixed(2);
                        //报损时，若是重量大于货箱内某已物品重量，则显示货箱内物品重量，否则显示称重重量
                        const goodsDetailId = $('#goods-detail-id').val();
                        const orderRow = $('#box-list-table').bootstrapTable('getRowByUniqueId', goodsDetailId);
                        if (orderRow) {
                            if (weight > orderRow.weight) {
                                $("#" + id).val(orderRow.weight);
                            } else {
                                $("#" + id).val(weight);
                            }
                        }

                    }
                } else {
                    $("#" + id).val(0);
                }
            } else {
                $("#" + id).val(0);
            }
        } else {
            if (bigProduct === 1) {
                $("#" + id).val(str);
            } else {
                $("#" + id).val(0);
            }
        }
    } else {
        if (type == 0) {
            const rows = $('#' + tableId).bootstrapTable('getSelections');
            if (rows.length > 0) {
                const row = rows[0];
                if (row.remainingWeight && row.remainingWeight > 0) {
                    $("#" + id).val(row.remainingWeight);
                } else {
                    $('#' + id).val(row.weight);
                }
            }
        } else if (type == 1) {
            const v = $('#' + id).val();
            if (v && v > 0) {
                $('#' + id).val("");
            }
        }
    }
}

//合箱称重
//type:0:称重；1:报损
function mergeWeight(reValue, tableId, id, type, bigProduct) {
    if (reValue != 0.000 && reValue > 0) {
        const str = reValue.replace(/\s*/g, "");
        const weight = parseFloat(str) * weightUnit.toFixed(2);
        const goodsDetailId = $('#goods-detail-id').val();
        const orderRow = $('#merge-table-list').bootstrapTable('getRowByUniqueId', goodsDetailId);
        if (orderRow) {
            if (weight > orderRow.weight) {
                $("#" + id).val(orderRow.weight);
            } else {
                $("#" + id).val(weight);
            }
        }
    } else {
        $('#' + id).val("");
    }
}

/**
 * 日期格式化
 * @param minSize
 * @param type
 * @param time
 * @param isReplace
 * @returns {*}
 */
function fmtDate(minSize, type, time, noReplace) {
    let data = new Date();
    if (time && !noReplace) {
        data = new Date(time.replace(/-/g, '/'));
    }
    const year = data.getFullYear();  //获取年
    let month = data.getMonth() + 1;    //获取月
    if (month < 10) {
        month = '0' + month;
    }
    let day = data.getDate(); //获取日
    if (day < 10) {
        day = '0' + day;
    }
    let hours = data.getHours();
    if (hours < 10) {
        hours = '0' + hours;
    }
    let minutes = data.getMinutes();
    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    let second = data.getSeconds();
    if (second < 10) {
        second = '0' + second;
    }
    if (type) {
        time = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + second;
    } else if (minSize == "year") {
        time = year + "年";
    } else if (minSize == "month") {
        time = year + "年" + month + "月";
    } else if (minSize == "day") {
        time = year + "年" + month + "月" + day + "日";
    } else if (minSize == "hours") {
        time = year + "年" + month + "月" + day + "日" + " " + hours;
    } else if (minSize == "minutes") {
        time = year + "年" + month + "月" + day + "日" + " " + hours + ":" + minutes;
    } else if (minSize == 'day_two') {
        time = year + "-" + month + "-" + day;
    } else {
        time = year + "年" + month + "月" + day + "日" + " " + hours + ":" + minutes + ":" + second;
    }
    return time;
}

/*
var opt = []
rows.push({
    id: startId + i,
    name: 'test' + (startId + i),
    price: '$' + (startId + i)
})*/

//bootstrapTable插入行
function insertRow(opt, tableId, top) {
    if (top) {
        //头部插入行
        $("#" + tableId).bootstrapTable('prepend', opt);
        $("#" + tableId).bootstrapTable('scrollTo', 0);
    } else {
        //尾部插入行
        $("#" + tableId).bootstrapTable('append', opt);
        $("#" + tableId).bootstrapTable('scrollTo', 'bottom');
    }
}

//检查是否为正整数
function isUnsignedInteger(a) {
    const reg = /^\d{1,2}$/;
    return reg.test(a);
}

//金额、重量校验
function checkPrice(price) {
    if (!price) {
        return false;
    }
    return (/^[1-9]\d{0,7}(\.\d{1,3})?$|^0(\.\d{1,3})?$/).test(price.toString());
}

//获取wcs响应
function selectResponseFromWcs(type, clientId, processType, confirm, callback) {
    const opt = {type: type, clientId: clientId, processType: processType};
    $.ajax({
        type: "POST",
        url: "/wcs/selectResponseFromWcs",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            console.log(type + "指令响应：" + JSON.stringify(data));
            if (data.code == 0) {
                if (data.data) {
                    if (data.data.code == 0) {
                        if (confirm) {
                            BootstrapDialog.confirm({
                                title: '信息提示',
                                message: '当前用户' + toCN(type) + '存在需处理信息，是否现在处理?',
                                btnCancelLabel: '取消', // <-- Default value is 'Cancel',
                                btnOKLabel: '处理', // <-- Default value is 'OK',
                                callback: function (result) {
                                    if (result) {
                                        callback(data, false, opt);
                                    } else {
                                        callback(data, true, opt);
                                    }
                                }
                            });
                        } else {
                            // delResponseFromWcs(data, opt);
                            callback(data, false, opt);
                        }
                    } else {
                        callback(data, false, opt);
                        /*delResponseFromWcs(data, opt);
                        if ($('#message-content').hasClass("message-content")) {
                            $('#message-content').text(data.data.msg);
                            setTimeout("$('#message-content').text('')", 5000);
                        } else {
                            BootstrapDialog.alert(data.data.msg);
                        }*/
                    }
                } else {
                    callback(null, false, opt);
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

function toCN(type) {
    let result = '';
    if (type) {
        switch (type) {
            case 'weighResp':
                result = "空箱出入库";
                break;
            case 'inBufferPos':
                result = "原料分拣";
                break;
            default:
                result = 'sortWeight';
        }
    }
    return result;
}

//删除响应
function delResponseFromWcs(result, opt) {
    $.ajax({
        type: "POST",
        url: "/wcs/delResponseFromWcs",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

function refreshLocalPage() {
    document.location.reload();
}

/**
 * 确认框覆盖，即先关闭再打开
 * @param title
 * @param msg
 * @param callback
 * @param obj
 */
let dialog = null;

function confirmReplace(title, msg, callback, obj) {
    if (dialog) {
        dialog.close();
    }
    dialog = new BootstrapDialog.confirm({
        title: title,
        message: msg,
        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
        btnOKLabel: '确定', // <-- Default value is 'OK',
        callback: function (result) {
            if (result) {
                if (callback != null) {
                    callback(obj);
                }
            } else {
            }
        }
    });
}